<script lang="ts" setup>
import { Ref } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

import Misc from '@core/utils/Misc';
import RouteHelper from '@core/utils/RouteHelper';
import Order, { RenewOrderParams } from '@core/engine/Order';
import SubViewContainer from '@core/components/subLayout/SubViewContainer.vue';
import * as Enums from '@firewall/engine/Enums';
import Firewall, { FirewallInstance } from '@firewall/engine/Firewall';

const route = useRoute();
const { t } = useI18n({ inheritLocale: true, useScope: 'local' });

const firewalls: Ref<Array<FirewallInstance>> = ref([]);
const fetchFirewalls = async () => {
  const response = await Firewall.fetchList({
    vpcIds: RouteHelper.queryValueToPlural(route.query.vpcIds),
  });
  firewalls.value = response.list || [];
};

const CycleTypeOptions = {
  Month: 'month',
  Year: 'year',
};
const CycleCountOptions = {
  [CycleTypeOptions.Month]: Misc.getIncrementArray(11, 1),
  [CycleTypeOptions.Year]: Misc.getIncrementArray(3, 1),
};
const cycleCountOptions: Ref<Array<number>> = ref([...CycleCountOptions[CycleTypeOptions.Month]]);
const renewOrderParams = reactive({
  autoPlay: true,
  cycleCount: 1,
  cycleType: CycleTypeOptions.Month,
  resourceIds: [] as Array<string>,
});

const isLoading = ref(false);
onMounted(async () => {
  isLoading.value = true;
  await fetchFirewalls();
  renewOrderParams.resourceIds = firewalls.value.map((firewall) => firewall.masterResourceId);
  isLoading.value = false;
  fetchTotalPrice();
});

const onTypeChange = (newType: string) => {
  renewOrderParams.cycleCount = 1;
  renewOrderParams.cycleType = newType;
  cycleCountOptions.value = CycleCountOptions[newType];
  fetchTotalPrice();
};
const onCountChange = (newCount: number) => {
  renewOrderParams.cycleCount = newCount;
  fetchTotalPrice();
};

const getRemoteParams = (): RenewOrderParams => {
  const { cycleType, cycleCount } = renewOrderParams;
  const remoteParams: RenewOrderParams = {
    ...renewOrderParams,
    cycleType: Enums.OrderCycleType.Month,
    cycleCount: 1,
  };
  if (cycleType === CycleTypeOptions.Month) {
    remoteParams.cycleType = Enums.OrderCycleType.Month;
    remoteParams.cycleCount = cycleCount;
  } else {
    switch (cycleCount) {
      case 1: remoteParams.cycleType = Enums.OrderCycleType.Year; break;
      case 2: remoteParams.cycleType = Enums.OrderCycleType.DoubleYears; break;
      case 3: remoteParams.cycleType = Enums.OrderCycleType.TripleYears; break;
      default: break;
    }
    renewOrderParams.cycleCount = 1;
  }
  return remoteParams;
};

const totalPrice = ref(0);
const isQueryingPrice = ref(true);
const fetchTotalPrice = async () => {
  isQueryingPrice.value = true;
  const response = await Order.queryRenewOrderPrice(getRemoteParams());
  totalPrice.value = response[0].totalPrice;
  isQueryingPrice.value = false;
};

const isAgreedToAgreement = ref(false);
const onRenewNow = async () => {
  if (!renewOrderParams.cycleCount || !renewOrderParams.cycleType) {
    return ElMessage.warning(t('noTimeSelectedMessage'));
  }
  if (!isAgreedToAgreement.value) {
    return ElMessage.warning(t('noAgreedMessage'));
  }
  isLoading.value = true;
  try {
    const response = await Order.placeRenewOrder(getRemoteParams());
    response.orderPlacedEvents.forEach((event) => {
      Order.openOrderDetailPage(event.newOrderId);
    });
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <SubViewContainer>
    <ElCard v-loading="isLoading">
      <ElRow>
        <ElTable size="small" :data="firewalls">
          <ElTableColumn :label="t('firewallName')" property="firewallName"/>
          <ElTableColumn :label="t('firewallEdition')">
            <template #default="scope">{{ t(`firewallEditions.${scope.row.firewallEdition}`) }}</template>
          </ElTableColumn>
          <ElTableColumn :label="t('quotaState')">
            <template #default="scope">{{ t(`quotaStates.${scope.row.firewallState}`) }}</template>
          </ElTableColumn>
          <ElTableColumn :label="t('vpc')">
            <template #default="scope">
              <div class="vpc">
                <div class="id">{{scope.row.vpcId}}</div>
                <div class="ip">{{scope.row.vpcIp}}</div>
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('expireAt')">
            <template #default="scope">
              {{scope.row.expireTime ? dayjs(scope.row.expireTime).format(t('dateFormat')) : '-'}}
            </template>
          </ElTableColumn>
        </ElTable>
      </ElRow>
      <ElRow class="select-row">
        <span>{{t('renewTime')}}</span>
        <ElSelect :model-value="renewOrderParams.cycleType" @change="onTypeChange">
          <ElOption v-for="item in CycleTypeOptions"
            :key="item"
            :label="t(`cycleTypes.${item}`)"
            :value="item"
          />
        </ElSelect>
        <ElSelect :model-value="renewOrderParams.cycleCount" @change="onCountChange">
          <ElOption v-for="item in cycleCountOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </ElSelect>
      </ElRow>
      <ElRow class="text-row">
        <TotalPrice :price="totalPrice" :is-loading="isQueryingPrice" />
      </ElRow>
      <ElRow class="text-row">
        <ElCheckbox v-model="isAgreedToAgreement" :label="t('agreeMessage')"/>
        <ElLink type="primary" :underline="false">{{t('serviceAgreement')}}</ElLink>
      </ElRow>
      <ElRow class="bottom-buttons">
        <ElButton type="primary" @click="onRenewNow">{{t('orderNow')}}</ElButton>
        <RouterLink :to="{ name: 'configCenter.quota' }">
          <ElButton>{{t('cancel')}}</ElButton>
        </RouterLink>
      </ElRow>
    </ElCard>
  </SubViewContainer>
</template>

<i18n lang="yaml" locale="zh-CN">
  firewallName: '云防火墙名称'
  firewallEdition: '配额规格'
  firewallEditions:
    AdvancedEdition: '高级版'
  quotaState: '配额状态'
  quotaStates:
    all: '全部'
    normal: '正常'
    overdue: '已过期'
    unsubscribe: '已退订'
  vpc: '虚拟私有云'
  expireAt: '配额到期时间'
  cancel: '取消'
  orderNow: '立即购买'
  renewTime: '续订时长:'
  cycleTypes:
    month: '月'
    year: '年'
  agreeMessage: '我已阅读并同意相关协议'
  serviceAgreement: '《天翼云云防火墙（原生版）服务协议》'
  noTimeSelectedMessage: '请先选择续订时长'
  noAgreedMessage: '请阅读并同意服务协议'
  dateFormat: 'YYYY-MM-DD'
</i18n>

<style lang="scss" scoped>
.select-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 50px 0;
  font-size: 14px;

  .el-select {
    width: 100px;
    margin-left: 20px;
  }
}

.text-row {
  margin-bottom: 40px;
  font-size: 14px;
}

.bottom-buttons {
  .el-button {
    margin-right: 10px;
  }
}
</style>
